<template>
  <div>
    <div ref='editor' id="div1"></div>
    <el-button type="primary" @click="submit">保存</el-button>
  </div>
</template>

<script>
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue'
import { findTools, addTools, updateTools } from '../../plugins/request'
import WangEditor  from 'wangeditor'
export default {
    setup() {
        const editor = ref();
        const state = reactive({
            data: {
                content: ''
            },
            isAddOrUpdate: null
        })
        let instance;
        onMounted(() => {
            selectTools()
            instance = new WangEditor(editor.value);
            instance.config.zIndex = 500
            instance.config.height = 400
            Object.assign(instance.config, {
                onchange() {
                    //console.log('change');
                },
            });
            instance.create();

        })
        onBeforeUnmount(() => {
            instance.destroy();
            instance = null;
        });
        const selectTools = async () => {
            let { data } = await findTools({})
            if(data.state = 1) {
                state.isAddOrUpdate = data.data.length == 0
                state.data = state.isAddOrUpdate ? {content: ''} : data.data[0]
                instance.txt.html(state.data.content)
            }
        }
        const submit = async () => {
            let html = instance.txt.html()
            let temp = html.replace(/<\/?.+?>/g, "");
            let result = temp.replace(/ /g, "");
            if(state.data.content == html){
                return ElMessage.error('未修改内容')
            }
            state.data.content = html
            if(state.data.content == '') {
                return ElMessage.error('未填写内容')
            }else{
                if(state.isAddOrUpdate){
                    //添加
                    let { data } = await addTools(state.data)
                    if(data.status == 1) ElMessage.success('添加成功')
                }else{
                    //修改
                    let { data } = await updateTools(state.data)
                    if(data.status == 1) ElMessage.success('修改成功')
                }
            }
        }
        return {
            submit,
            editor
        }
    }
}
</script>

<style scoped>
#div1{
    margin-bottom: 20px;
}
</style>